<?php

require_once "Basic.php";

class Login extends BasicEntity {
  
  private static $loginName = "login";
  private static $passWordName = "password";
  private static $loginAsName = "loginAs";
  
  private static $action = "Login";
  
  private $ok;
  private $tiposLogin;
  
  public function __construct() {
    $this->tiposLogin = array(
        LOGGED_CLIENT => "Cliente",
        LOGGED_EMPLOYEE => "Funcion&aacute;rio",
        LOGGED_ADMIN => "Administrador"
    );
    $this->fields = array (
        new FormField(true, Login::$loginName, "Login", new FormFieldTextLine()),
        new FormField(true, Login::$passWordName, "Senha", new FormFieldPassword()),
        new FormField(true, Login::$loginAsName, "Logar Como", new FormFieldChoice($this->tiposLogin))
    );
    $this->ok = false;
    $this->processFields();
  }
  
  public function actionDescription() {
    return Login::$action;
  }
  
  /**
   * 
   * @param array $userInput Dados do usuário. Provavelmente $_POST.
   * @return boolean True se login foi feito com sucesso, ou false caso algo tenha aconteicdo para "barrar" o login.
   * Dados inválidos por exemplo.
   */
  protected function actionLogin($userInput) {
    $login = $userInput[Login::$loginName];
    $loginAs = $userInput[Login::$loginAsName];
    $pwd = $userInput[Login::$passWordName];
    
    $db = new DBUtils();
    
    try {
      $db->connect();
      switch($loginAs) {
        case LOGGED_ADMIN:
          if(preg_match("%^[0-9]+$%", $login) === 1) {
            $login = intval($login);
          }
          else {
            goto invalidLogin;
          }
          $db->runQuery("select idMatriz as id, senha from Matriz where idMatriz = ? and ativo=1", array($login));
          break;
        case LOGGED_EMPLOYEE:
          if(preg_match("%^[0-9]+$%", $login)) {
            $login = intval($login);
          }
          else {
            goto invalidLogin;
          }
          $db->runQuery("select idFilial as id, senha from Filial where idFilial = ? and ativo=1", array($login));
          break;
        case LOGGED_CLIENT:
          $db->runQuery("select idCliente as id,senha from Cliente where email = ? and ativo=1", array($login));
          break;
      }
      $item = $db->getItem();
      if($item === null || $item->senha !== $pwd) {
        goto invalidLogin;
      }
      $_SESSION[SESSION_LOGGED_AS] = $loginAs;
      $_SESSION[SESSION_LOGIN] = $item->id;
      $db->close();
    }
    catch(DBError $e) {
      $db->close();
      logMessage($e->errors, "Login_DBError");
      return "Falha no banco de dados. O erro foi reportado.";
    }
    
    $this->ok = true;
    return true;
    
    invalidLogin:
    $this->fields[Login::$loginAsName]->setValid(false);
    $this->fields[Login::$loginName]->setValid(false);
    $this->fields[Login::$passWordName]->setValid(false);
    $db->close();
    return "Login/Senha inv&aacute;lidos.";
  }
  
  public function passed() {
    return $this->ok;
  }
  
}

$page = new Page("Login");
$user = new Login();
if(isset($_SESSION[SESSION_LOGIN])) {
  $page->addContent("<p>Voc&ecirc; j&aacute; est&aacute; logado.</p>");
}
else {
  $form = new StdForm($user, $_GET, $_POST, "", "", "Login.php");
  $form->processForm();
  if($user->passed()) {
    header("Location: index.php");
  }
  else {
    $page->addContent($form->getHtml());
  }
}
echo $page->getHtml();
